import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Select,
  Upload,
  AutoComplete,
  Progress,
} from 'antd';
import React, { useState, useRef, forwardRef, useImperativeHandle, useEffect } from 'react';
import axios from 'axios';
import { FormattedMessage, history, Link } from 'umi';
import ProTable from '@ant-design/pro-table';
import { uploadImage, getPvc } from '../service';
import { getGroupList } from '../../NameSpace/service';
// import e from 'express';
import * as tus from 'tus-js-client';
import { CHUNK_SIZE } from '@/utils/const';

let uploadDict = {};
const { Option } = Select;

const ImageUpload = (props, ref) => {
  const [show, setShow] = useState(false);
  const [data, setData] = useState([]);
  const [tempList, setTempList_] = useState({}); // 上传列表对象
  const [fileList, setFileList] = useState([]);  // 文件列表
  const [nameSpace, setNameSpace] = useState([]); // 用户组名称列表
  const [nowNamseSpace, setNowNameSpace] = useState(null);
  const [stop, setStop] = useState(false);
  const [imageId, setImageId] = useState(0);

  // const [uploadDict,setUploadDict] = useState(0)


  function setTempList(e) {
    setTempList_(e);
    setFileList(Object.values(e));
  }
  // 打开弹窗操作
  useImperativeHandle(ref, () => ({
    open: (info={}) => {
      if (info.id) {
        setImageId(info.id);
      }
      // 获取用户组列表
      getGroupList({ pageNum: 1, pageSize: 40 }).then((res) => {
        if (res.code === 0) {
          setNameSpace(res.data.userGroups); // 保存用户组列表
        }
      });
      setShow(true);
    },
    close: () => {
      // 重置
      setTempList({});
      setNowNameSpace(null);
      setShow(false);
      setImageId(0);
    },
  }));

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 300,
      render: (text) => (
        <div
          style={{
            width: '270px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {text}
        </div>
      ),
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      render: (text) => {
        return <span>{Number(Number(text) / 1048576).toFixed(2)} MB</span>;
      },
    },
    {
      title: '任务进度',
      dataIndex: 'percent',
      key: 'percent',
      render: (percent) => {
        if (percent < 100) {
          return <Progress percent={percent} status="active" />;
        }
        if (percent == 100) {
          return <span style={{ color: 'green' }}>上传成功</span>;
        }
      },
    },
    {
      title: React.$i18n('操作'),
      key: 'address',
      render(text, record, index) {
        // console.log(record);
        console.log(fileList);
        console.log(tempList);
        return (
          <>
            {(record.status == 'init' || record.status == 'parse') && (
              <Button
                type="text"
                onClick={() => {
                  if (record.size > 2 * 1024 * 1024 * 1024) {
                    message.error('上传文件超过 2G');
                    return;
                  }
                  console.log(tempList);
                  let name = record.name;
                  if (tempList[name].status == 'init') {
                    tempList[name].status = 'pending';
                    setTempList(tempList);
                    uploadSingle(name);
                  } else {
                    tempList[name].status = 'pending';
                    let upload = uploadDict[record.name];
                    setTempList(tempList);
                    upload.start();
                  }
                }}
              >
                上传
              </Button>
            )}
            {record.status == 'pending' && (
              <Button
                type="text"
                onClick={() => {
                  let name = record.name;
                  let upload = uploadDict[record.name];
                  upload.abort();

                  tempList[name].status = 'parse';
                  setTempList(tempList);
                }}
              >
                暂停
              </Button>
            )}

            <a style={{ color: 'red' }} onClick={() => removeRecord(record, index)}>
              {React.$i18n('删除')}
            </a>
          </>
        );
      },
    },
  ];
  // 取消在下一个版本
  function handleCancel() {}

  // 控制上传进度
  function addPercent(name, percent) {
    console.log('tempList', tempList);
    let p = tempList[name].percent;
    tempList[name].percent = percent;
    setTempList(tempList);
  }

  // 全部取消在后面版本
  function stopAll() {}

  // 单个上传
  function uploadSingle(name) {
    let upload = uploadDict[name];
    upload.start();
  }

  // 删除列表单项
  function removeRecord(e, i) {
    let name = e.name;
    let newFileList = JSON.parse(JSON.stringify(tempList));
    delete newFileList[name];
    delete uploadDict[name];
    setTempList(newFileList);
  }

  // 添加文件
  function addFile(e) {
    console.log(e);
    setFileList(e.fileList);
    let files = e.fileList;
    console.log(fileList);
    let name = e.name;

    let old_list = tempList;
    files.forEach((e) => {
      console.log(e.status);
      if (!e.status) {
        e.percent = 0;
        e.status = 'init';
        e.file = e.originFileObj;
        old_list[e.name] = e;

        let name = e.name;
        const file = e.file;

        let upload = new tus.Upload(file, {
          endpoint: `/file-server/api/v1/files`,
          retryDelays: [0, 3000, 5000, 10000, 20000],
          metadata: {
            filename: file.name,
            filetype: file.type,
            moduleName: 'apharbor',
          },
          chunkSize: CHUNK_SIZE,
          headers: {
            Location: 2500,
          },
          onError: function (error) {
            console.log('Failed because: ' + error);
          },
          onProgress: (sent, size) => {
            let percent = Number((sent * 100) / size).toFixed(2);
            addPercent(name, percent);
          },
          onSuccess: function () {
            let id = upload.url.split('/');
            id = id[id.length - 1];

            tempList[name].status = 'success';
            console.log(tempList);
            setTempList(tempList);

            getPvc(id).then((res) => {
              if (res.code === 0) {
                let temp = tempList;
                let storage = res.data.storagePath;
                temp[file.name].storagePath = storage;
                setTempList(temp);
                console.log(tempList);
                let data_ = {
                  storagePath: storage,
                };
                if (imageId) {
                  data_.imageId = parseInt(imageId);
                }
                const link = res.data.downloadLink.split('/');
                data_.fileId = link[link.length - 1]; // 后台增加 fileserver 上传成功后的文件Id
                uploadImage(data_).then((res) => {
                  props.success();
                });
              }
            });
          },
        });

        upload.findPreviousUploads().then(function (previousUploads) {
          // Found previous uploads so we select the first one.
          console.log(previousUploads);
          if (previousUploads.length) {
            upload.resumeFromPreviousUpload(previousUploads[0]);
          }
          // Start the upload
          uploadDict[e.name] = upload;
        });
      }
    });
    console.log(old_list);
    setTempList(old_list);

    // uploadDict[e.name] = null;
  }

  // 全部上传
  function uploadAll() {
    console.log('tempList', tempList);
    console.log('fileList', fileList);

    Object.keys(tempList).map((name) => {
      let upload = uploadDict[name];
      if (tempList[name].status == 'init'||tempList[name].status == 'parse') {
        tempList[name].status = 'pending';
        console.log(tempList);
        setTempList(tempList);
        let upload = uploadDict[name];
        upload.start();
      }
    });
  }

  // 全部取消
  function cancalAll(){
    Object.keys(uploadDict).map((name) => {
      if(tempList[name].status=='pending'){
        let upload = uploadDict[name];
        upload.abort();
        tempList[name].status = 'parse';
      }
      setTempList(tempList);

    });
    setStop(true);
  }

  return (
    <div>
      <Modal
        title="添加镜像"
        visible={show}
        onCancel={handleCancel}
        width="900px"
        footer={null}
        onCancel={() => {
          ref.current.close();
        }}
        maskClosable={false}
      >

        <div>
          您还可以添加10个镜像压缩包，文件大小（含解压后）不得超过 2 GB，支持
          tar、tar.gz格式，仅支持上传1.11.2及以上容器引擎客户端版本制作的镜像压缩包。
        </div>
        <div style={{ margin: '10px 0px', display: 'flex' }}>
          <Upload
            name="files"
            fileList={fileList}
            onChange={addFile}
            multiple
            beforeUpload={(file) => {
              const biggerThan2G = file.size / (1024 * 1024 * 1024) > 2;
              if (biggerThan2G) {
                message.error('只支持最大2G内容');
              }
              // return !biggerThan2G;
              return false; // 手动上传
            }}
            showUploadList={false}
            accept=".tar.gz,.tar,.zip,.iso"
            maxCount="10"
          >
            <Button type="primary" style={{ marginRight: '10px' }}>
              选择镜像文件
            </Button>
          </Upload>
          {fileList.length > 0 && (
            <div>
              <Button
                onClick={() => {
                  console.log(tempList);
                  console.log(fileList);
                  if (fileList.some(f => f.size > 2 * 1024 * 1024 * 1024)) {
                    message.error('文件列表中存在超过 2G 文件');
                    return;
                  }

                  uploadAll();
                }}
                style={{ marginRight: '10px' }}
              >
                全部上传
              </Button>
              <Button
                onClick={() => {
                  cancalAll()

                }}
                style={{ marginRight: '10px' }}
              >
                取消上传
              </Button>
            </div>
          )}
        </div>
        <Table columns={columns} dataSource={fileList} rowKey={(row) => row.name} />
      </Modal>
    </div>
  );
};

const rImageUpload = React.forwardRef(ImageUpload);

export default rImageUpload;
